<template>
  <div class="app-container receipt-container">
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="90%" max-width="1400px" draggable overflow @close="handleDialogClose">
      <el-form :model="form" class="receipt-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据类型">
              <el-select v-model="form.orderType" placeholder="请选择" class="form-field">
                <el-option
                  v-for="dict in orderTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户">
              <el-select v-model="form.customer" placeholder="请选择" class="form-field">
                <el-option
                  v-for="item in merchantList"
                  :key="item.id"
                  :label="item.merchantName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种">
              <el-select v-model="form.currency" placeholder="请选择" class="form-field">
                <el-option label="人民币" value="人民币" />
                <!-- 其他币种选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="汇率">
              <el-input v-model="form.exchangeRate" placeholder="请输入" class="form-field" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发票类型">
              <el-select v-model="form.invoiceType" placeholder="请选择" class="form-field">
                <el-option label="普通发票" value="普通发票" />
                <!-- 其他发票类型选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算单位">
              <el-input v-model="form.settlementUnit" disabled class="form-field" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算方式">
              <el-select v-model="form.settlementMethod" placeholder="请选择" class="form-field">
                <!-- 结算方式选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已结算金额">
              <el-input v-model="form.settledAmount" placeholder="请输入" class="form-field" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收款日期">
              <el-date-picker v-model="form.paymentDate" type="date" placeholder="选择日期" class="form-field" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="compact-table-container">
          <el-table 
            :data="form.products" 
            style="min-width: 1100px; width: 100%" 
            class="compact-table flat-table" 
            border 
            :stripe="true"
            :cell-style="{ padding: '1px' }"
            @selection-change="handleSelectionChange"
            ref="productTable"
          >
            <el-table-column type="selection" width="40" align="center" v-if="batchDeleteMode" />
            <el-table-column prop="warehouseName" label="仓库名称" width="100" header-align="center">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.areaId"
                  class="compact-input no-arrow flat-input"
                  @change="(val) => handleWarehouseChange(val, $index)"
                >
                  <el-option
                    v-for="item in areaList"
                    :key="item.id"
                    :label="item.areaName"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="productCode" label="货品编号" width="100" header-align="center">
              <template #default="{ row, $index }">
                <el-autocomplete
                  v-model="row.productCode"
                  :fetch-suggestions="(q, cb) => handleSearch(q, cb, 'productCode', $index)"
                  @select="item => handleSelectProduct($index, item)"
                  value-key="value"
                  :debounce="300"
                  class="compact-input no-arrow flat-input"
                  popper-class="product-autocomplete-dropdown"
                  :disabled="!form.customer"
                  :placeholder="form.customer ? '请输入' : '请先选择客户'"
                >
                  <template #default="{ item }">
                    <div class="product-item" :class="{ 'customer-used-item': item.isCustomerItem }">
                      <span class="product-code">{{ item.productCode || '-' }}</span> - 
                      <span class="product-name">{{ item.productName || '-' }}</span>
                      <span class="product-quantity">(库存: {{ item.inventory || 0 }})</span>
                      <span v-if="item.isCustomerItem" class="customer-used-tag">常用</span>
                    </div>
                  </template>
                </el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="货品名称" min-width="250" header-align="center">
              <template #default="{ row, $index }">
                <div class="product-name-container">
                <el-autocomplete
                  v-model="row.productName"
                    :fetch-suggestions="(q, cb) => handleSearch(q, cb, 'productName', $index)"
                  @select="item => handleSelectProduct($index, item)"
                    value-key="value"
                    :debounce="300"
                    class="compact-input no-arrow flat-input"
                    popper-class="product-autocomplete-dropdown"
                    :disabled="!form.customer"
                    :placeholder="form.customer ? '请输入' : '请先选择客户'"
                  >
                    <template #default="{ item }">
                      <div class="product-item" :class="{ 'customer-used-item': item.isCustomerItem }">
                        <span class="product-code">{{ item.productCode || '-' }}</span> - 
                        <span class="product-name">{{ item.productName || '-' }}</span>
                        <span class="product-quantity">(库存: {{ item.inventory || 0 }})</span>
                        <span v-if="item.isCustomerItem" class="customer-used-tag">常用</span>
                      </div>
                    </template>
                  </el-autocomplete>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="70" header-align="center">
              <template #default="{ row, $index }">
                <el-autocomplete
                  v-model="row.unit"
                  :fetch-suggestions="(q, cb) => handleSearchUnits(q, cb)"
                  @select="item => handleSelectUnit(item, $index)"
                  value-key="value"
                  :debounce="300"
                  class="compact-input no-arrow flat-input"
                >
                  <template #default="{ item }">
                    <div>{{ item.unit }}</div>
                  </template>
                </el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="70" header-align="center" align="right">
              <template #default="{ row, $index }">
                <el-input
                  v-model.number="row.quantity"
                  class="compact-input number-input flat-input"
                  @input="calculateAmount($index)"
                  @change="(val) => handleQuantityChange($index, val)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="90" header-align="center" align="right">
              <template #default="{ row, $index }">
                <el-input
                  v-model.number="row.price"
                  class="compact-input number-input flat-input"
                  @input="calculateAmount($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="90" header-align="center" align="right">
              <template #default="{ row, $index }">
                <el-input
                  v-model.number="row.amount"
                  class="compact-input number-input flat-input"
                  @input="calculateQuantityOrPrice($index)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="gift" label="赠品" width="60" header-align="center">
              <template #default="{ row }">
                <el-switch v-model="row.gift" />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" header-align="center">
              <template #default="{ row, $index }">
                <el-autocomplete
                  v-model="row.remark"
                  :fetch-suggestions="(q, cb) => handleSearch(q, cb, 'remark', $index)"
                  @select="item => handleSelectProduct($index, item)"
                  class="compact-input no-arrow flat-input"
                />
              </template>
            </el-table-column>
            <el-table-column prop="attachment" label="附项" min-width="170" header-align="center">
              <template #default="{ row, $index }">
                <el-autocomplete
                  v-model="row.attachment"
                  :fetch-suggestions="(q, cb) => handleSearch(q, cb, 'attachment', $index)"
                  @select="item => handleSelectProduct($index, item)"
                  @keydown="event => handleAttachmentTab(event, $index)"
                  class="compact-input no-arrow flat-input"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50" header-align="center" align="center">
              <template #default="{ $index }">
                <el-button 
                  type="danger" 
                  :icon="Delete" 
                  circle 
                  size="small"
                  class="delete-btn"
                  @click="deleteProductRow($index)"
                  :disabled="form.products.length <= 1 || batchDeleteMode"
                  v-if="!batchDeleteMode"
                />
              </template>
            </el-table-column>
            <template #append>
              <el-table-row class="summary-row">
                <el-table-column>
                  <template #default>合计</template>
                </el-table-column>
                <el-table-column />
                <el-table-column />
                <el-table-column />
                <el-table-column>
                  <template #default>{{ totalQuantity }}</template>
                </el-table-column>
                <el-table-column />
                <el-table-column>
                  <template #default>{{ totalAmount }}</template>
                </el-table-column>
                <el-table-column />
                <el-table-column />
                <el-table-column />
                <el-table-column />
                <el-table-column />
              </el-table-row>
            </template>
          </el-table>
        </div>
        <div class="table-actions">
          <template v-if="!batchDeleteMode">
            <el-button class="mt-2" @click="addProductRow" type="primary" plain size="small" :icon="Plus">新增一行</el-button>
            <el-button 
              class="mt-2" 
              @click="startBatchDelete" 
              type="danger" 
              plain 
              size="small" 
              :icon="Delete"
              :disabled="form.products.length <= 1"
            >批量删除</el-button>
          </template>
          
          <template v-else>
            <span class="selection-tip">
              已选择 {{ selectedRows.length }} 项
            </span>
            <el-button 
              type="danger" 
              size="small" 
              :icon="Delete"
              @click="confirmBatchDelete"
              :disabled="selectedRows.length === 0 || selectedRows.length >= form.products.length"
            >确认删除</el-button>
            <el-button 
              type="info" 
              size="small"
              @click="cancelBatchDelete"
            >取消</el-button>
          </template>
        </div>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="6">
            <el-form-item label="制单人">
              <el-select v-model="form.creator" placeholder="请选择" class="form-field">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.nickName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核人">
              <el-select v-model="form.reviewer" placeholder="请选择" class="form-field">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.nickName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select v-model="form.salesperson" placeholder="请选择" class="form-field">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.nickName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-form-item label="附加说明">
              <el-input type="textarea" v-model="form.additionalInfo" placeholder="请输入" class="form-field" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleSave">保存新增</el-button>
          <el-button type="primary" @click="handleConfirm">暂存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Receipt">
import { ref, computed, watch, onMounted, nextTick, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import { getItemsByMerchant, listMerchantItemNoPage, updateMerchantItem, addMerchantItem, 
         batchSaveMerchantItems, batchUpdateMerchantItems, saveTempOrderItems, 
         getTempOrderItems, getItemsWithInventoryBatch } from '@/api/wms/merchantItem'
import { listItem, listItemGroupBySku } from '@/api/wms/item'
import { listAreaNoPage } from '@/api/wms/area'
import { listInventory, listInventoryBoard } from '@/api/wms/inventory'
import { listMerchantNoPage } from '@/api/wms/merchant'
import { listUser } from '@/api/system/user'
import { getDicts } from '@/api/system/dict/data'

const { proxy } = getCurrentInstance()

// 商品行接口
interface ProductRow {
  areaId: number | null
  warehouseName?: string
  productCode: string
  productName: string
  unit: string
  quantity: number | null
  price: number
  amount: number
  gift: boolean
  remark: string
  attachment: string
  itemId: string | number
  skuId?: string | number
  stockQuantity?: number
  inventory?: number  // 库存数量
  fromHistory?: boolean  // 是否是客户历史商品
  isCustomerItem?: boolean  // 是否是客户常用商品
  value?: string  // 用于下拉框显示的值
  priority?: number  // 优先级
}

interface ReceiptForm {
  orderType: string
  customer: string
  currency: string
  exchangeRate: number
  invoiceType: string
  settlementUnit: string
  settlementMethod: string
  settledAmount: number
  paymentDate: string
  products: ProductRow[]
  creator?: string
  reviewer?: string
  salesperson?: string
  additionalInfo?: string
}

const props = defineProps<{ modelValue: boolean; title: string }>()
const emit = defineEmits(['modelValue', 'title'])

const dialogVisible = ref(props.modelValue)
const dialogTitle = ref(props.title)

// 区域数据
const areaList = ref([])
// 客户数据
const merchantList = ref([])
// 用户数据
const userList = ref([])
// 单据类型数据
const orderTypeOptions = ref([])

// 获取区域数据
onMounted(() => {
  fetchAreas()
  fetchMerchants()
  fetchUsers()
  fetchOrderTypes()
})

const fetchAreas = async () => {
  try {
    const res = await listAreaNoPage({})
    if (res.data) {
      areaList.value = res.data
    }
  } catch (error) {
    console.error('获取库区列表失败', error)
  }
}

// 获取客户数据
const fetchMerchants = async () => {
  try {
    const res = await listMerchantNoPage({})
    if (res.data) {
      merchantList.value = res.data
    }
  } catch (error) {
    console.error('获取客户列表失败', error)
  }
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    const res = await listUser({})
    if (res.rows) {
      userList.value = res.rows
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
  }
}

// 获取单据类型数据
const fetchOrderTypes = async () => {
  try {
    const res = await getDicts('wms_shipment_type')
    if (res.data) {
      orderTypeOptions.value = res.data
    }
  } catch (error) {
    console.error('获取单据类型失败', error)
  }
}

const initialForm: ReceiptForm = {
  orderType: '',
  customer: '',
  currency: '人民币',
  exchangeRate: 1,
  invoiceType: '普通发票',
  settlementUnit: '纪隆德国际贸易温州有限公司',
  settlementMethod: '',
  settledAmount: 0,
  paymentDate: '',
  products: [
    {
      areaId: null,
      warehouseName: '',
      productCode: '',
      productName: '',
      unit: '',
      quantity: null,
      price: 0,
      amount: 0,
      gift: false,
      remark: '',
      attachment: '',
      itemId: '',
      skuId: '',
      stockQuantity: 0,
      inventory: 0,
      fromHistory: false,
      isCustomerItem: false
    }
  ]
}

const form = ref<ReceiptForm>({ ...initialForm })

watch(
  () => props.modelValue,
  (newValue) => {
    dialogVisible.value = newValue
    if (newValue) {
      // 创建当前日期对象
      const today = new Date()
      // 格式化为YYYY-MM-DD格式
      const formattedDate = today.toISOString().split('T')[0]
      
      form.value = { 
        ...initialForm, 
        paymentDate: formattedDate, // 设置默认收款日期为今天
        products: initialForm.products.map(p => ({ ...p })) 
      }
    }
  }
)
watch(
  () => props.title,
  (newValue) => {
    dialogTitle.value = newValue
  }
)

function addProductRow() {
  form.value.products.push({
    areaId: null,
    warehouseName: '',
    productCode: '',
    productName: '',
    unit: '',
    quantity: null,
    price: 0,
    amount: 0,
    gift: false,
    remark: '',
    attachment: '',
    itemId: '',
    skuId: '',
    stockQuantity: 0,
    inventory: 0,
    fromHistory: false,
    isCustomerItem: false
  });
}

// Function to delete a product row
function deleteProductRow(index: number) {
  // Prevent deleting the last row
  if (form.value.products.length <= 1) {
    ElMessage.warning('至少保留一行商品');
    return;
  }
  
  // Confirm deletion
  ElMessageBox.confirm(`确定要删除第 ${index + 1} 行商品吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // Remove the row at the specified index
    form.value.products.splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => {
    // User cancelled the deletion
  });
}

// 修改fetchProductSuggestions函数，优先使用客户历史记录
async function fetchProductSuggestions(query: string, field: keyof ProductRow, index: number): Promise<ProductRow[]> {
  try {
    const row = form.value.products[index]
    const areaId = row.areaId
    
    // 如果没有选择库区，无法获取商品
    if (!areaId) {
      return []
    }
    
    // 如果没有选择客户，无法获取商品
    if (!form.value.customer) {
      ElMessage.warning('请先选择客户后再查询商品')
      return []
    }
      
    const merchantId = Number(form.value.customer)
    if (isNaN(merchantId)) {
      console.error('客户ID必须是数字类型')
      return []
    }
    
    let suggestions: ProductRow[] = []
    
    try {
      // 首先获取客户历史记录 - 这是最重要的数据源
      console.log('首先获取客户历史记录')
      const historyRes = await getItemsWithInventoryBatch(merchantId)
      let customerHistoryItems = []
      
      if (historyRes && historyRes.data && historyRes.data.length > 0) {
        customerHistoryItems = historyRes.data
        console.log('获取到客户历史记录:', customerHistoryItems.length)
        
        // 根据查询条件过滤客户历史记录
        const filteredHistory = customerHistoryItems.filter((history: any) => {
          if (!query || query.trim() === '') return true; // 如果没有查询词，返回所有历史记录
          
          if (field === 'productCode' && history.itemCode) {
            return history.itemCode.toLowerCase().includes(query.toLowerCase())
          } else if (field === 'productName' && history.itemName) {
            return history.itemName.toLowerCase().includes(query.toLowerCase())
          } else if (field === 'remark' && history.remark) {
            return history.remark.toLowerCase().includes(query.toLowerCase())
          }
          return false
        })
        
        console.log('匹配查询条件的历史记录:', filteredHistory.length)
        
        // 将客户历史记录转换为建议列表，设置优先级为1（最高）
        filteredHistory.forEach((history: any) => {
          suggestions.push({
            itemId: history.itemId,
            productCode: history.itemCode || '',
            productName: history.itemName || '',
            skuId: history.skuId || '',
            inventory: history.stockQuantity || 0,
            stockQuantity: history.stockQuantity || 0,
            areaId: row.areaId,
            unit: history.unit || '',
            price: history.price || 0,
            quantity: history.quantity || null,
            amount: 0,
            gift: false,
            remark: history.remark || '',
            attachment: '',
            fromHistory: true,
            isCustomerItem: true,
            value: `${history.itemCode || ''} - ${history.itemName || ''} (${history.stockQuantity || 0})`,
            priority: 1 // 客户历史记录优先级最高
          })
        })
      }

      // 如果需要更多结果或没有客户历史记录，再获取库存数据
      if (suggestions.length < 10) {
        // 构建查询参数
        const boardParams = {
          areaId: areaId,
          pageNum: 1,
          pageSize: 100
        }
        
        // 根据搜索条件添加查询参数
        if (query) {
          if (field === 'productCode') {
            boardParams['itemCode'] = query
          } else if (field === 'productName') {
            boardParams['itemName'] = query
          }
        }
        
        console.log('查询库存看板参数:', boardParams)
        
        // 使用库存看板接口获取当前库区的库存数据
        const boardRes = await listInventoryBoard(boardParams, 'warehouse')
        
        if (boardRes && boardRes.rows && boardRes.rows.length > 0) {
          console.log('从库存看板获取到商品数量:', boardRes.rows.length)
          
          // 转换响应数据为建议列表
          const inventoryItems = boardRes.rows.map((item: any) => {
            // 提取商品信息
            const itemObj = item.item || {}
            const skuObj = item.itemSku || {}
            
            // 检查是否已经在客户历史记录中
            const existsInHistory = suggestions.some(s => 
              s.itemId === (item.itemId || skuObj.itemId || itemObj.id) &&
              (!s.skuId && !item.skuId || s.skuId === item.skuId)
            )
            
            // 只有不在客户历史记录中的商品才添加
            if (!existsInHistory) {
              return {
                itemId: item.itemId || skuObj.itemId || itemObj.id,
                productCode: itemObj.itemCode || '',
                productName: itemObj.itemName || '',
                skuId: item.skuId || skuObj.id,
                inventory: item.quantity || 0,
                stockQuantity: item.quantity || 0,
                areaId: areaId,
                unit: itemObj.unit || '',
                price: skuObj.sellingPrice || 0,
                quantity: null,
                amount: 0,
                gift: false,
                remark: '',
                attachment: '',
                fromHistory: false,
                isCustomerItem: false,
                value: `${itemObj.itemCode || ''} - ${itemObj.itemName || ''} (${item.quantity || 0})`,
                priority: item.quantity > 0 ? 2 : 3 // 有库存的优先级为2，无库存的为3
              }
            }
            return null
          }).filter(Boolean) // 过滤掉null值
          
          // 添加到建议列表中
          suggestions = [...suggestions, ...inventoryItems]
        }
      }
      
      // 如果仍然没有足够的结果，尝试从商品表获取基本数据
      if (suggestions.length < 5) {
        console.log('尝试从商品表获取基础数据')
        
        const itemParams = {
          pageNum: 1,
          pageSize: 50
        }
        
        // 添加查询条件
        if (query) {
          if (field === 'productCode') {
            itemParams['itemCode'] = query
          } else if (field === 'productName') {
            itemParams['itemName'] = query
          }
        }
        
        const itemRes = await listItem(itemParams)
        
        if (itemRes && itemRes.rows && itemRes.rows.length > 0) {
          const items = itemRes.rows
          console.log('从商品表获取到数据:', items.length)
          
          // 将商品表数据转换为建议列表
          const baseItems = items
            .filter(item => {
              // 检查是否已经在之前的结果中
              return !suggestions.some(s => 
                s.itemId === item.id &&
                (!s.skuId && !item.skuId || s.skuId === item.skuId)
              )
            })
            .map(item => ({
              itemId: item.id,
              productCode: item.itemCode || '',
              productName: item.itemName || item.name || '',
              skuId: item.skuId || '',
              inventory: 0, // 库存为0
              stockQuantity: 0,
              areaId: row.areaId,
              unit: item.unit || '',
              price: item.price || item.standardPrice || 0,
              quantity: null,
              amount: 0,
              gift: false,
              remark: '',
              attachment: '',
              fromHistory: false,
              isCustomerItem: false,
              value: `${item.itemCode || ''} - ${item.itemName || item.name || ''} (0)`,
              priority: 4 // 商品表中的商品优先级最低
            }))
          
          // 添加到建议列表中
          suggestions = [...suggestions, ...baseItems]
        }
      }
    } catch (error) {
      console.error('查询商品数据失败:', error)
      ElMessage.error('查询商品信息失败，请重试')
    }
    
    // 按照优先级排序：客户历史记录 > 有库存商品 > 无库存商品 > 商品表数据
    suggestions.sort((a, b) => {
      // 首先按照优先级排序
      const priorityA = a.priority || (a.isCustomerItem ? 1 : (a.inventory > 0 ? 2 : 3))
      const priorityB = b.priority || (b.isCustomerItem ? 1 : (b.inventory > 0 ? 2 : 3))
      
      if (priorityA !== priorityB) return priorityA - priorityB
      
      // 同优先级内，按库存数量从大到小排序
      return (b.inventory || 0) - (a.inventory || 0)
    })
    
    console.log('最终的商品建议列表:', suggestions.length)
    return suggestions
  } catch (error) {
    console.error('获取商品建议失败:', error)
    ElMessage.error('获取商品建议失败，请重试')
    return []
  }
}

watch(
  [() => form.value.orderType, () => form.value.customer],
  async ([newOrderType, newCustomer], [oldOrderType, oldCustomer]) => {
    // 只有当单据类型和客户都有值，且其中一个发生变化时才查询
    if (newOrderType && newCustomer && (newOrderType !== oldOrderType || newCustomer !== oldCustomer)) {
      await loadHistoryRecords();
    }
  }
)

// 从历史记录加载数据
async function loadHistoryRecords() {
  try {
    // 如果没有选择客户或单据类型，不进行查询
    if (!form.value.customer || !form.value.orderType) {
      return;
    }
    
    console.log('查询历史记录，客户ID:', form.value.customer, '单据类型:', form.value.orderType);
    
    // 确保客户ID是数字类型
    const merchantId = Number(form.value.customer);
    if (isNaN(merchantId)) {
      console.error('客户ID必须是数字类型');
      return;
    }
    
    // 调用批量查询接口，一次性获取客户关联商品和库存信息
    try {
      const res = await getItemsWithInventoryBatch(merchantId);
    
    if (res.data && res.data.length > 0) {
        console.log('找到客户商品关联记录和库存信息:', res.data);
      
      // 清空当前商品列表
      form.value.products = [];
      
        // 填充商品数据
        for (const item of res.data) {
          try {
            // 直接使用整合好的数据填充表单
            form.value.products.push({
              areaId: item.areaId,
              warehouseName: item.warehouseName || '',
              productCode: item.itemCode || '',
              productName: item.itemName || '',
              unit: item.unit || '',
              quantity: item.quantity || null,
              price: item.price || 0,
              amount: (item.price || 0) * (item.quantity || 0),
              gift: false,
              remark: item.remark || '',
              attachment: '',
              itemId: item.itemId,
              skuId: item.skuId,
              stockQuantity: item.stockQuantity || 0,
              inventory: item.stockQuantity || 0,
              fromHistory: item.fromCustomerHistory || false,
              isCustomerItem: item.isCustomerItem || false
            });
          } catch (itemError) {
            console.error('加载单个商品数据失败:', itemError);
            // 继续处理下一个商品
          }
        }
      
      // 如果没有记录，添加一个空行
      if (form.value.products.length === 0) {
        addProductRow();
      }
    } else {
      console.log('未找到历史记录');
      // 如果当前没有行，添加一个空行
        if (form.value.products.length === 0) {
          addProductRow();
        }
      }
    } catch (apiError) {
      console.error('调用批量查询接口失败:', apiError);
      ElMessage.warning('获取历史记录失败，将使用空白表单');
      // 确保至少有一行
      if (form.value.products.length === 0) {
        addProductRow();
      }
    }
  } catch (error) {
    console.error('加载历史记录失败:', error);
    // 出错时确保至少有一行
    if (form.value.products.length === 0) {
      addProductRow();
    }
  }
}

// 当选择商品时的处理函数
function handleSelectProduct(index: number, item: ProductRow) {
  // 填充选中的商品信息
  form.value.products[index].productCode = item.productCode
  form.value.products[index].productName = item.productName
  form.value.products[index].unit = item.unit
  form.value.products[index].price = item.price
  form.value.products[index].itemId = item.itemId
  form.value.products[index].skuId = item.skuId
  form.value.products[index].remark = item.remark || ''
  form.value.products[index].isCustomerItem = item.isCustomerItem || false
  
  // 如果商品有库存信息，显示库存提示
  if (item.inventory !== undefined) {
    // 保存当前库存量，用于后续验证
    form.value.products[index].stockQuantity = item.inventory
    
    // 为常用商品添加视觉标识
    if (item.isCustomerItem) {
      console.log('该商品是客户常用商品')
    }
  }
  
  // 如果商品有价格信息，自动计算金额
  calculateAmount(index)
  
  // 如果有更多行，自动聚焦到下一行
  if (index < form.value.products.length - 1) {
    // 使用nextTick确保DOM已更新
    nextTick(() => {
      const nextInput = document.querySelector(`#product-row-${index + 1} input:first-child`)
      if (nextInput) {
        (nextInput as HTMLElement).focus()
      }
    })
  } else {
    // 如果是最后一行，添加新行
    addProductRow()
  }
}

function handleAttachmentTab(event: KeyboardEvent, index: number) {
  if (event.key === 'Tab' && index === form.value.products.length - 1) {
    addProductRow()
  }
}

const totalQuantity = computed(() =>
  form.value.products.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
)
const totalAmount = computed(() =>
  form.value.products.reduce((sum, item) => sum + Number(item.amount || 0), 0)
)

// 修改handleSave函数，实现保存新增功能
function handleSave() {
  // 验证表单数据
  if (!validateForm()) {
    return
  }

  // 保存订单数据
  saveOrderData(true) // 参数true表示保存新增
  
  // 更新客户关联商品记录
  updateCustomerHistory()
  
  // 关闭对话框
  dialogVisible.value = false
  form.value = { ...initialForm, products: initialForm.products.map(p => ({ ...p })) }
  emit('modelValue', false)
}

// 修改handleConfirm函数，实现暂存功能
function handleConfirm() {
  // 验证表单数据
  if (!validateForm()) {
    return
  }
  
  // 执行暂存操作（保存为临时订单）
  saveTempOrder()
  
  // 关闭对话框
  dialogVisible.value = false
  form.value = { ...initialForm, products: initialForm.products.map(p => ({ ...p })) }
  emit('modelValue', false)
}

// 验证表单数据
function validateForm() {
  // 检查客户是否已选择
  if (!form.value.customer) {
    ElMessage.warning('请选择客户')
    return false
  }
  
  // 检查是否有商品
  const validProducts = form.value.products.filter(p => p.productName && p.itemId)
  if (validProducts.length === 0) {
    ElMessage.warning('请至少添加一个商品')
    return false
  }
  
  return true
}

// 保存订单数据
function saveOrderData(isNewOrder = false) {
  // 构建订单数据
  const orderData = {
    orderType: form.value.orderType,
    customerId: form.value.customer,
    currency: form.value.currency,
    exchangeRate: form.value.exchangeRate,
    invoiceType: form.value.invoiceType,
    settlementUnit: form.value.settlementUnit,
    settlementMethod: form.value.settlementMethod,
    settledAmount: form.value.settledAmount,
    paymentDate: form.value.paymentDate,
    creator: form.value.creator,
    reviewer: form.value.reviewer,
    salesperson: form.value.salesperson,
    additionalInfo: form.value.additionalInfo,
    isNew: isNewOrder, // 标记是否为新订单
    products: form.value.products.filter(p => p.productName && p.itemId) // 只保存有效的商品行
  }
  
  console.log('保存订单数据:', orderData)
  
  // 保存订单数据，但不显示提示消息
  if (isNewOrder) {
    // 这里应该调用后端API保存新订单数据
    // 例如: addShipmentOrder(orderData).then(...)
  } else {
    // 更新订单数据
    // 例如: updateShipmentOrder(orderData).then(...)
  }
}

// 暂存订单（临时保存）
function saveTempOrder() {
  // 构建临时订单数据，加入日期信息
  const today = new Date()
  const tempOrderData = {
    orderType: form.value.orderType,
    customerId: form.value.customer,
    currency: form.value.currency,
    exchangeRate: form.value.exchangeRate,
    invoiceType: form.value.invoiceType,
    settlementUnit: form.value.settlementUnit,
    settlementMethod: form.value.settlementMethod,
    settledAmount: form.value.settledAmount,
    paymentDate: form.value.paymentDate,
    creator: form.value.creator,
    reviewer: form.value.reviewer,
    salesperson: form.value.salesperson,
    additionalInfo: form.value.additionalInfo,
    createDate: today.toISOString(), // 添加创建日期
    expireDate: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59).toISOString(), // 当天结束时间
    products: form.value.products.filter(p => p.productName && p.itemId) // 只保存有效的商品行
  }
  
  console.log('暂存订单数据:', tempOrderData)
  
  // 直接保存商品关联信息，而不是调用临时订单API
  updateCustomerHistory()
}

function handleCancel() {
  dialogVisible.value = false
  form.value = { ...initialForm, products: initialForm.products.map(p => ({ ...p })) }
  emit('modelValue', false)
}

function handleDialogClose() {
  dialogVisible.value = false
  emit('modelValue', false)
  form.value = { ...initialForm, products: initialForm.products.map(p => ({ ...p })) }
}

// 处理单位搜索，去除重复单位
async function handleSearchUnits(query: string, cb: (results: any[]) => void) {
  try {
    // 使用 inventory/list 接口查询单位
    const inventoryParams: any = {
      pageNum: 1,
      pageSize: 50
    };
    
    if (query) {
      inventoryParams.unit = query;
    }
    
    const res = await listInventory(inventoryParams);
    
    if (res.rows && res.rows.length > 0) {
      // 使用Set去重
      const uniqueUnits = new Set();
      const results = [];
      
      res.rows.forEach(item => {
        const unit = item.item?.unit;
        if (unit && !uniqueUnits.has(unit)) {
          uniqueUnits.add(unit);
          results.push({
            unit: unit,
            value: unit
          });
        }
      });
      
      cb(results);
    } else {
      cb([]);
    }
  } catch (error) {
    console.error('获取单位失败', error);
    cb([]);
  }
}

// 计算单行金额
function calculateAmount(index: number) {
  const row = form.value.products[index]
  
  // 如果数量和价格都有值，计算金额
  if (row.quantity !== null && row.price !== null) {
    row.amount = row.quantity * row.price
    
    // 检查库存
    if (row.stockQuantity !== undefined && row.quantity > row.stockQuantity) {
      ElMessage({
        message: `警告：${row.productName} 的请求数量 ${row.quantity} 超过当前库存 ${row.stockQuantity}`,
        type: 'warning',
        duration: 5000
      })
    }
  } else {
    row.amount = 0
  }
  
  // 不需要单独调用calculateTotalAmount，totalAmount已经是计算属性会自动更新
}

// 根据金额计算数量或单价
function calculateQuantityOrPrice(index: number) {
  const row = form.value.products[index];
  
  // 如果有金额和单价，计算数量
  if (row.amount !== null && row.price !== null && row.price !== 0 && 
      row.amount !== undefined && row.price !== undefined) {
    row.quantity = parseFloat((row.amount / row.price).toFixed(2));
  }
  // 如果有金额和数量，计算单价
  else if (row.amount !== null && row.quantity !== null && row.quantity !== 0 && 
           row.amount !== undefined && row.quantity !== undefined) {
    row.price = parseFloat((row.amount / row.quantity).toFixed(2));
  }
}

// 处理单位选择
function handleSelectUnit(item, index) {
  form.value.products[index].unit = item.unit;
}

// 修改handleWarehouseChange函数，选择仓库时检查客户是否已选择
const handleWarehouseChange = (areaId, index) => {
  const area = areaList.value.find(a => a.id === areaId)
  form.value.products[index].warehouseName = area ? area.areaName : ''
  form.value.products[index].productCode = ''
  form.value.products[index].productName = ''
  form.value.products[index].unit = ''
  form.value.products[index].remark = ''
  
  // 如果还没有选择客户，提示用户先选择客户
  if (!form.value.customer) {
    ElMessage.warning('请先选择客户，再选择商品')
  }
}

// 恢复handleSearch函数
async function handleSearch(query: string, cb: (results: ProductRow[]) => void, field: keyof ProductRow, index: number) {
  // 验证已选择库区
  const row = form.value.products[index]
  if (!row.areaId) {
    cb([]);
    return;
  }
  
  // 调用fetchProductSuggestions获取商品建议
  const apiResults = await fetchProductSuggestions(query, field, index);
  cb(apiResults);
}

// 自定义模板渲染建议项
const renderItem = (item) => {
  return {
    value: item.value,
    productCode: item.productCode,
    productName: item.productName,
    unit: item.unit,
    price: item.price,
    remark: item.remark
  }
}

// 添加数量变更监听函数，检查库存是否足够
const handleQuantityChange = (index, val) => {
  const row = form.value.products[index]
  
  // 如果有库存数量，并且输入的数量大于库存，给出警告
  if (row.stockQuantity !== undefined && row.quantity !== null && row.quantity > row.stockQuantity) {
    ElMessageBox.alert(`警告：所需数量(${row.quantity})超过库存数量(${row.stockQuantity})`, '库存不足警告', {
      confirmButtonText: '继续',
      callback: () => {
        // 用户确认后继续
        calculateAmount(index)
      }
    })
  } else {
    calculateAmount(index)
  }
}

// 更新客户历史记录
function updateCustomerHistory() {
  if (!form.value.customer) {
    console.error('更新客户历史记录失败: 客户ID不能为空')
    return
  }
  
  const merchantId = Number(form.value.customer)
  if (isNaN(merchantId)) {
    console.error('更新客户历史记录失败: 客户ID必须是数字类型')
    return
  }
  
  // 准备要更新和添加的数据
  const validProducts = form.value.products.filter(p => p.itemId && p.productName)
  if (validProducts.length === 0) {
    console.warn('没有有效的商品数据需要更新')
    return
  }
  
  // 设置加载状态
  const isProcessing = ref(true)
  
  // 转换为merchantItem格式，确保保存价格但不保存item_spec字段
  const merchantItems = validProducts.map(product => ({
    merchantId: merchantId,
    itemId: product.itemId,
    skuId: product.skuId,
    itemCode: product.productCode,
    itemName: product.productName,
    unit: product.unit,
    price: product.price,
    quantity: product.quantity || 1,
    amount: product.price ? product.price * (product.quantity || 1) : 0,
    remark: product.remark || ''
  }))
  
  // 批量保存/更新客户商品关联记录
  batchSaveMerchantItems(merchantItems)
    .then(results => {
      console.log('客户商品关联记录更新成功')
      ElMessage.success('已成功保存客户商品关联记录')
      isProcessing.value = false
    })
    .catch(error => {
      console.error('更新客户商品关联记录失败:', error)
      ElMessage.error('保存客户商品关联记录失败，请重试')
      isProcessing.value = false
    })
}

// 表格引用
const productTable = ref(null);

// 用于存储选中的行
const selectedRows = ref([]);

// 批量删除模式标志
const batchDeleteMode = ref(false);

// 处理选择变更
function handleSelectionChange(selection) {
  selectedRows.value = selection;
}

// 启动批量删除模式
function startBatchDelete() {
  batchDeleteMode.value = true;
  selectedRows.value = [];
  
  // 切换到批量删除模式后，需要等待下一个渲染周期，表格列才会更新
  nextTick(() => {
    // 确保表格和选择列已经渲染完成
    if (productTable.value) {
      // 可以在这里添加其他初始化逻辑，如自动选中某些行等
    }
  });
}

// 取消批量删除模式
function cancelBatchDelete() {
  batchDeleteMode.value = false;
  selectedRows.value = [];
}

// 确认批量删除
function confirmBatchDelete() {
  // 如果没有选择任何行，给出提示
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一行进行删除');
    return;
  }

  // 如果用户尝试删除所有行，阻止操作
  if (selectedRows.value.length >= form.value.products.length) {
    ElMessage.warning('必须至少保留一行商品');
    return;
  }

  // 确认删除
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 行商品吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 获取选中行的索引
    const indexesToDelete = selectedRows.value.map(row => 
      form.value.products.findIndex(item => item === row)
    ).sort((a, b) => b - a); // 倒序排列，从后往前删除，避免索引变化问题
    
    // 执行删除
    indexesToDelete.forEach(index => {
      if (index !== -1) {
        form.value.products.splice(index, 1);
      }
    });
    
    // 如果删除后没有行，添加一个空行
    if (form.value.products.length === 0) {
      addProductRow();
    }
    
    // 成功提示
    ElMessage.success(`成功删除 ${indexesToDelete.length} 行`);
    
    // 退出批量删除模式
    batchDeleteMode.value = false;
    selectedRows.value = [];
  }).catch(() => {
    // 用户取消删除，不执行任何操作
  });
}

// 处理对话框关闭时，确保退出批量删除模式
watch(dialogVisible, (newVal) => {
  if (!newVal && batchDeleteMode.value) {
    batchDeleteMode.value = false;
    selectedRows.value = [];
  }
});
</script>

<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.details {
  display: flex;
  gap: 10px;
}
.form {
  margin-top: 20px;
}
.form-group {
  margin-bottom: 10px;
}
.product-table {
  margin-top: 20px;
}
.footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.custom-table {
  font-size: 12px;
}
.custom-input {
  width: 100%;
  font-size: 12px;
  padding: 2px 4px;
}
.compact-table-container {
  width: 100%;
  overflow-x: auto;
  max-width: 100%;
}
.compact-table {
  font-size: 12px;
  table-layout: fixed;
  width: 100%;
  
  // 允许表格在小屏上水平滚动而不会破坏布局
  :deep(.el-table__inner-wrapper) {
    overflow-x: auto;
  }
  
  :deep(.el-table__body) {
    width: 100% !important;
  }
  
  :deep(.el-table__header) th {
    background: #f5f7fa;
    height: 24px;
    padding: 2px 0;
    font-weight: normal;
  }
  
  :deep(.el-table__body) td {
    height: 28px;
    padding: 1px 0;
  }
  
  :deep(.el-table__cell) {
    padding: 1px 0;
    line-height: 1.2;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal; /* 允许文本换行 */
  }
  
  :deep(.el-table__row--striped) {
    background-color: #f8f8f9;
  }
  
  :deep(.summary-row) {
    background-color: #f5f7fa;
    font-weight: bold;
  }
}

.flat-table {
  :deep(.el-table__border-left),
  :deep(.el-table__border-right),
  :deep(.el-table__border-top),
  :deep(.el-table__border-bottom) {
    border-color: #dcdfe6 !important;
  }
  
  :deep(.el-table__cell) {
    border-color: #dcdfe6 !important;
  }
  
  // 移除表格单元格聚焦边框
  :deep(.el-table__row:focus),
  :deep(.el-table__row:focus-within),
  :deep(.el-table__cell:focus),
  :deep(.el-table__cell:focus-within) {
    outline: none !important;
  }
  
  // 移除表格hover效果
  :deep(.el-table__row:hover) td {
    background-color: inherit !important;
  }
  
  :deep(.el-table__row--striped:hover) td {
    background-color: #f8f8f9 !important;
  }
}

.flat-input {
  :deep(.el-input__wrapper),
  :deep(.el-autocomplete__wrapper) {
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }
  
  :deep(.el-input__inner) {
    border: none !important;
    background-color: transparent !important;
    height: 24px !important;
    line-height: 24px !important;
    padding-left: 8px !important;
  }
  
  // 取消聚焦时的蓝色边框和阴影
  :deep(.el-input__wrapper:hover),
  :deep(.el-input__wrapper.is-focus),
  :deep(.el-input.is-focus .el-input__wrapper),
  :deep(.el-autocomplete.is-focus .el-input__wrapper) {
    box-shadow: none !important;
    border-color: transparent !important;
  }
  
  // 取消输入框的聚焦样式
  :deep(.el-input__inner:focus),
  :deep(.el-input__inner:active) {
    outline: none !important;
    border-color: transparent !important;
    box-shadow: none !important;
  }
  
  // 统一下拉框样式
  :deep(.el-select__popper),
  :deep(.el-autocomplete__popper) {
    border: 1px solid #dcdfe6 !important;
  }
  
  // 移除选择框和自动完成框的选中边框
  :deep(.el-select .el-input.is-focus .el-input__wrapper),
  :deep(.el-select .el-input__wrapper.is-focus),
  :deep(.el-autocomplete.is-focus .el-input__wrapper) {
    box-shadow: none !important;
  }
}

// 点击选择时不显示边框
:deep(.el-select-dropdown__item.selected),
:deep(.el-select-dropdown__item:hover),
:deep(.el-autocomplete-suggestion__item:hover),
:deep(.el-autocomplete-suggestion__item.highlighted) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
}

.product-name-container {
  width: 100%;
  :deep(.el-autocomplete) {
    width: 100%;
  }
}

.ellipsis-text {
  max-width: 100%;
  white-space: normal;
  word-break: break-word;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.no-arrow {
  :deep(.el-input__suffix) {
    display: none !important;
  }
  :deep(.el-input__inner) {
    padding-left: 8px !important; /* 调整左侧内边距，使文字与左侧对齐 */
  }
  :deep(.el-select__popper) {
    min-width: auto !important;
  }
}

.number-input {
  :deep(.el-input__inner) {
    text-align: right;
    padding-right: 8px;
  }
}

// 移除输入框点击选中的边框
:deep(.el-input.is-active .el-input__wrapper) {
  box-shadow: none !important;
}

// 移除select聚焦轮廓
:deep(.el-select:focus-within) {
  outline: none !important;
}

// 为所有输入框和选择框添加通用样式
:deep(.el-input),
:deep(.el-select),
:deep(.el-autocomplete) {
  &:hover, &:focus, &:active, &.is-active, &.is-focus {
    .el-input__wrapper {
      box-shadow: none !important;
    }
  }
}

// 禁止选中后的边框
:deep(*:focus) {
  outline: none !important;
}

// 禁止选中后的边框 - 更强制的方式
:deep(*) {
  outline: none !important;
}

// 重写所有表单元素样式，使其统一
.receipt-container {
  // 移除所有输入框和下拉框的边框和阴影
  :deep(.el-select .el-input__wrapper),
  :deep(.el-input__wrapper),
  :deep(.el-autocomplete .el-input__wrapper) {
    box-shadow: none !important;
    background-color: transparent !important;
    border: none !important;
    padding: 0 !important;
  }
  
  // 移除所有状态下的边框和阴影
  :deep(.el-input__wrapper.is-focus),
  :deep(.el-input.is-focus .el-input__wrapper),
  :deep(.el-autocomplete.is-focus .el-input__wrapper),
  :deep(.el-input__wrapper:hover),
  :deep(.el-input__wrapper:active),
  :deep(.el-input__wrapper.is-active),
  :deep(.el-select .el-input__wrapper),
  :deep(.el-select .el-input__wrapper.is-focus),
  :deep(.el-select .el-input.is-focus .el-input__wrapper) {
    box-shadow: none !important;
    border: none !important;
    background-color: transparent !important;
  }
  
  // 移除输入框内部元素的边框和背景
  :deep(.el-input__inner) {
    border: none !important;
    background-color: transparent !important;
  }
  
  // 确保输入框文字与左边对齐且没有多余的内边距
  :deep(.el-input__inner) {
    padding-left: 8px !important;
    border-radius: 0 !important;
  }
  
  // 移除所有下拉箭头
  :deep(.el-input__suffix),
  :deep(.el-select__caret) {
    display: none !important;
  }
  
  // 确保下拉菜单样式统一
  :deep(.el-select-dropdown),
  :deep(.el-autocomplete-suggestion) {
    border: 1px solid #dcdfe6 !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  }
  
  // 移除元素的点击/聚焦轮廓
  :deep(*:focus),
  :deep(*:focus-visible),
  :deep(*:focus-within) {
    outline: none !important;
  }
  
  // 确保表格样式统一
  :deep(.el-table) {
    --el-table-border-color: #dcdfe6 !important;
    --el-table-border: 1px solid var(--el-table-border-color) !important;
    --el-table-text-color: #606266 !important;
    --el-table-header-text-color: #909399 !important;
    --el-table-header-bg-color: #f5f7fa !important;
    --el-table-row-hover-bg-color: transparent !important;
  }
  
  // 移除表格hover效果
  :deep(.el-table__row:hover) > td.el-table__cell {
    background-color: inherit !important;
  }
  
  :deep(.el-table__row--striped:hover) > td.el-table__cell {
    background-color: #f8f8f9 !important;
  }
  
  // 确保所有表单控件完全统一
  :deep(.flat-input) {
    .el-input__wrapper,
    .el-autocomplete__wrapper {
      background: none !important;
      border: none !important;
      box-shadow: none !important;
      padding: 0 !important;
    }
    
    &:hover, &:focus, &:active, &.is-focus {
      .el-input__wrapper,
      .el-autocomplete__wrapper {
        box-shadow: none !important;
        border: none !important;
      }
    }
  }
}

// 进一步确保聚焦状态下没有边框
:deep(.el-input.is-focus),
:deep(.el-autocomplete.is-focus),
:deep(.el-select.is-focus) {
  .el-input__wrapper {
    box-shadow: none !important;
  }
}

// 确保数字输入框右对齐
.number-input {
  :deep(.el-input__inner) {
    text-align: right !important;
    padding-right: 8px !important;
  }
}

// 针对特定字段的额外样式调整
.product-name-container {
  width: 100%;
  
  :deep(.el-autocomplete),
  :deep(.el-input) {
    width: 100%;
    
    .el-input__wrapper {
      box-shadow: none !important;
      padding: 0 !important;
    }
  }
}

// 确保下拉菜单样式统一
:deep(.el-select-dropdown),
:deep(.el-autocomplete-suggestion) {
  border: 1px solid #dcdfe6 !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
}

// 为产品名称的下拉菜单设置最小宽度
:deep(.el-autocomplete-suggestion__wrap) {
  min-width: 300px !important;
}

:deep(.el-autocomplete-suggestion__list) {
  max-width: 450px !important;
}

:deep(.el-popper.is-pure.is-light.el-autocomplete__popper) {
  min-width: 300px !important;
  max-width: 450px !important;
}

// 商品项样式
.product-item {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding: 4px 0;
}

.product-code {
  font-weight: bold;
  margin-right: 5px;
  color: #409EFF;
}

.product-name {
  flex: 1;
  word-break: break-word;
  white-space: normal;
}

.product-quantity {
  margin-left: 5px;
  color: #67C23A;
}

// 客户常用商品样式增强
.customer-used-item {
  background-color: #f0f9eb;
  border-left: 3px solid #67c23a;
  padding-left: 5px;
  margin-bottom: 4px;
  border-radius: 3px;
  position: relative;
  
  // 左侧绿色边框
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 3px;
    background-color: #67c23a;
  }
  
  // 客户常用商品的字体颜色加深
  .product-code {
    color: #2c6ecb;
    font-weight: 700;
  }
  
  .product-name {
    font-weight: 500;
    color: #333;
  }
  
  .product-quantity {
    font-weight: 500;
    color: #409EFF;
  }
}

.customer-used-tag {
  display: inline-block;
  padding: 2px 4px;
  background-color: #67c23a;
  color: white;
  border-radius: 2px;
  font-size: 12px;
  margin-left: 5px;
  font-weight: bold;
}

// 下拉菜单样式
:deep(.product-autocomplete-dropdown) {
  min-width: 350px !important;
  max-width: 500px !important;
  
  .el-autocomplete-suggestion__wrap {
    max-height: 280px !important;
  }
  
  .el-autocomplete-suggestion__list {
    padding: 5px !important;
  }
  
  .el-scrollbar__view {
    overflow-wrap: break-word !important;
  }
}

// 确保产品名称单元格内容可见
.product-name-container {
  width: 100%;
  height: 100%;
  
  :deep(.el-autocomplete) {
    width: 100%;
    height: 100%;
  }
  
  :deep(.el-input__wrapper) {
    height: 100%;
  }
  
  :deep(.el-input__inner) {
    height: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-word;
    line-height: 1.2;
  }
}

// 确保弹框内的表格容器能够适应不同屏幕尺寸
:deep(.el-dialog__body) {
  padding: 10px 20px;
  max-width: 100%;
}

// 为表单字段添加下划线效果（表格外）
.receipt-container {
  // 表单样式 - 应用到表格外的所有表单项
  :deep(.receipt-form) {
    .el-row {
      .el-form-item {
        .el-input__wrapper, 
        .el-select .el-input__wrapper,
        .el-date-editor .el-input__wrapper {
          box-shadow: none !important;
          border: none !important;
          border-bottom: 1px solid #dcdfe6 !important;
          border-radius: 0 !important;
          padding: 1px 8px !important;
          background-color: transparent !important;
          transition: border-color 0.3s;
        }
        
        .el-input__wrapper:hover,
        .el-select .el-input__wrapper:hover,
        .el-date-editor .el-input__wrapper:hover {
          border-bottom-color: #909399 !important;
        }
        
        .el-input__wrapper.is-focus,
        .el-select .el-input__wrapper.is-focus,
        .el-date-editor .el-input__wrapper.is-focus {
          border-bottom-color: #333 !important;
        }
        
        .el-input__inner {
          padding-left: 0 !important;
        }
      }
    }
  }
}

/* 确保表格内的元素不受影响 */
.receipt-container .compact-table-container :deep(.el-input__wrapper),
.receipt-container .compact-table-container :deep(.el-select .el-input__wrapper),
.receipt-container .compact-table-container :deep(.el-autocomplete .el-input__wrapper) {
  border: none !important;
  border-radius: 0 !important;
  border-bottom: none !important;
  box-shadow: none !important;
}

// 表单项下划线样式
.receipt-form :deep(.form-field) {
  .el-input__wrapper,
  &.el-input .el-input__wrapper, 
  &.el-select .el-input__wrapper,
  &.el-date-editor .el-input__wrapper {
    box-shadow: none !important;
    border: none !important;
    border-bottom: 1px solid #dcdfe6 !important;
    border-radius: 0 !important;
    background-color: transparent !important;
    transition: border-color 0.3s !important;
  }

  &:hover .el-input__wrapper,
  &.el-input:hover .el-input__wrapper,
  &.el-select:hover .el-input__wrapper,
  &.el-date-editor:hover .el-input__wrapper {
    border-bottom-color: #909399 !important;
  }

  &.is-focus .el-input__wrapper,
  &.el-input.is-focus .el-input__wrapper,
  &.el-select.is-focus .el-input__wrapper,
  &.el-date-editor.is-focus .el-input__wrapper {
    border-bottom-color: #333 !important;
  }
}

// Add styles for the table actions and delete button
.table-actions {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px; // 按钮之间的间距
  
  .selection-tip {
    margin-right: 10px;
    color: #606266;
    font-size: 13px;
    font-weight: bold;
  }
}

.delete-btn {
  padding: 2px;
  height: 22px;
  width: 22px;
  
  :deep(.el-icon) {
    font-size: 12px;
  }
}

// Make sure the operations column buttons are properly sized
.el-table {
  :deep(.cell) {
    .el-button.is-circle {
      padding: 2px;
    }
  }
}

// 确保表格选择列的样式一致
.el-table {
  :deep(.el-table-column--selection .cell) {
    padding-top: 3px;
    padding-bottom: 3px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  :deep(.el-checkbox) {
    height: 14px;
    margin-right: 0;
  }
  
  :deep(.el-checkbox__inner) {
    width: 14px;
    height: 14px;
  }
}

// 批量删除模式下的样式调整
.batch-delete-mode {
  background-color: #fef0f0;
  
  :deep(.el-table__row) {
    background-color: #fef0f0;
  }
  
  :deep(.el-table__row--striped) {
    background-color: #fef5f5;
  }
}
</style>